<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserAbility;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class UserAbilityController extends Controller
{
    /**
     * 获取用户能力数据
     */
    public function index(User $user, Request $request)
    {
        // 检查是否为当前用户或有权限查看
        if ($user->id !== $request->user()->id) {
            return $this->error('无权查看其他用户的能力数据', 403);
        }

        $timeRange = $request->get('time_range', 'all');
        
        $cacheKey = "user_abilities_{$user->id}_{$timeRange}";
        
        $abilities = Cache::remember($cacheKey, 1800, function () use ($user, $timeRange) {
            $query = $user->abilities()->orderBy('created_at');

            switch ($timeRange) {
                case '7d':
                    $query->where('created_at', '>=', now()->subDays(7));
                    break;
                case '30d':
                    $query->where('created_at', '>=', now()->subDays(30));
                    break;
                // 'all' 不需要额外条件
            }

            return $query->get();
        });

        if ($abilities->isEmpty()) {
            return $this->error('还没有能力数据，请先完成初始评估', 404);
        }

        $latestAbility = $abilities->last();
        $baselineAbility = $abilities->where('is_baseline', true)->first();

        $response = [
            'current_abilities' => [
                'breaking_ice' => $latestAbility->breaking_ice,
                'empathy' => $latestAbility->empathy,
                'conversation_flow' => $latestAbility->conversation_flow,
                'total_score' => $latestAbility->getTotalScore(),
            ],
            'radar_data' => $latestAbility->getRadarData(),
            'weakest_ability' => $latestAbility->getWeakestAbility(),
            'improvement_suggestions' => $this->getImprovementSuggestions($latestAbility),
            'has_improvement' => false,
            'improvement_data' => null,
        ];

        // 如果有基准数据，计算提升情况
        if ($baselineAbility && $latestAbility->id !== $baselineAbility->id) {
            $improvements = [
                'breaking_ice' => $latestAbility->breaking_ice - $baselineAbility->breaking_ice,
                'empathy' => $latestAbility->empathy - $baselineAbility->empathy,
                'conversation_flow' => $latestAbility->conversation_flow - $baselineAbility->conversation_flow,
            ];

            $hasSignificantImprovement = collect($improvements)->some(function ($improvement) {
                return $improvement >= 10; // 提升10分以上算显著提升
            });

            $response['has_improvement'] = $hasSignificantImprovement;
            $response['improvement_data'] = [
                'baseline_scores' => $baselineAbility->getRadarData(),
                'improvements' => $improvements,
                'total_improvement' => array_sum($improvements),
            ];
        }

        return $this->success($response, '获取用户能力数据成功');
    }

    /**
     * 获取用户能力历史数据
     */
    public function history(User $user, Request $request)
    {
        // 检查是否为当前用户或有权限查看
        if ($user->id !== $request->user()->id) {
            return $this->error('无权查看其他用户的能力历史', 403);
        }

        $fromDate = $request->get('from_date');
        $toDate = $request->get('to_date');

        $query = $user->abilities()->orderBy('created_at');

        if ($fromDate) {
            $query->where('created_at', '>=', $fromDate);
        }

        if ($toDate) {
            $query->where('created_at', '<=', $toDate);
        }

        $abilities = $query->get();

        if ($abilities->isEmpty()) {
            return $this->error('指定时间范围内没有能力数据', 404);
        }

        $historyData = $abilities->map(function ($ability) {
            return [
                'id' => $ability->id,
                'breaking_ice' => $ability->breaking_ice,
                'empathy' => $ability->empathy,
                'conversation_flow' => $ability->conversation_flow,
                'total_score' => $ability->getTotalScore(),
                'is_baseline' => $ability->is_baseline,
                'created_at' => $ability->created_at,
            ];
        });

        // 计算趋势
        $trends = $this->calculateTrends($abilities);

        return $this->success([
            'history' => $historyData,
            'trends' => $trends,
            'summary' => [
                'total_records' => $abilities->count(),
                'date_range' => [
                    'from' => $abilities->first()->created_at,
                    'to' => $abilities->last()->created_at,
                ],
                'highest_scores' => [
                    'breaking_ice' => $abilities->max('breaking_ice'),
                    'empathy' => $abilities->max('empathy'),
                    'conversation_flow' => $abilities->max('conversation_flow'),
                ],
            ]
        ], '获取能力历史数据成功');
    }

    /**
     * 获取改进建议
     */
    private function getImprovementSuggestions($ability)
    {
        $suggestions = [];
        
        if ($ability->breaking_ice < 60) {
            $suggestions[] = [
                'ability' => 'breaking_ice',
                'title' => '提升破冰技巧',
                'suggestion' => '尝试从环境观察开始对话，比如聊聊当下的活动或天气。记住，真诚的赞美是很好的破冰方式。',
            ];
        }

        if ($ability->empathy < 60) {
            $suggestions[] = [
                'ability' => 'empathy',
                'title' => '增强共情能力',
                'suggestion' => '多练习倾听技巧，尝试理解对方的感受而不是急于给建议。用"我能理解你的感受"来表达共情。',
            ];
        }

        if ($ability->conversation_flow < 60) {
            $suggestions[] = [
                'ability' => 'conversation_flow',
                'title' => '改善对话推进',
                'suggestion' => '学会问开放性问题，从对方的回答中找到新的话题点。分享相关的个人经历能让对话更深入。',
            ];
        }

        // 如果所有能力都不错，给出进阶建议
        if (empty($suggestions)) {
            $weakest = $ability->getWeakestAbility();
            $suggestions[] = [
                'ability' => $weakest,
                'title' => '继续精进',
                'suggestion' => '你的社交技能已经很不错了！可以尝试挑战更高难度的AI角色来进一步提升。',
            ];
        }

        return $suggestions;
    }

    /**
     * 计算能力趋势
     */
    private function calculateTrends($abilities)
    {
        if ($abilities->count() < 2) {
            return [
                'breaking_ice' => 'stable',
                'empathy' => 'stable',
                'conversation_flow' => 'stable',
            ];
        }

        $first = $abilities->first();
        $last = $abilities->last();

        return [
            'breaking_ice' => $this->getTrendDirection($first->breaking_ice, $last->breaking_ice),
            'empathy' => $this->getTrendDirection($first->empathy, $last->empathy),
            'conversation_flow' => $this->getTrendDirection($first->conversation_flow, $last->conversation_flow),
        ];
    }

    /**
     * 获取趋势方向
     */
    private function getTrendDirection($oldValue, $newValue)
    {
        $diff = $newValue - $oldValue;
        
        if ($diff > 5) {
            return 'improving';
        } elseif ($diff < -5) {
            return 'declining';
        } else {
            return 'stable';
        }
    }
}